import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import Cookies from 'js-cookie'
import {
  loginApi,
  getUserInfoApi,
  getUserListApi,
  createUserApi,
  updateUserApi,
  deleteUserApi,
  resetPasswordApi,
  checkUsernameApi,
  checkEmailApi,
  checkPhoneApi,
  type User,
  type UserCreateDTO,
  type UserUpdateDTO,
  type UserQueryDTO,
  type PageResult
} from '@/api/user'

export interface UserInfo {
  id: number
  username: string
  realName: string
  email: string
  phone: string
  avatar?: string
  roles: string[]
}

export const useUserStore = defineStore('user', () => {
  const token = ref<string>(Cookies.get('token') || '')
  const userInfo = ref<UserInfo | null>(null)

  // 用户管理相关状态
  const userList = ref<User[]>([])
  const userTotal = ref(0)
  const loading = ref(false)

  const isLoggedIn = computed(() => !!token.value)

  // 认证相关方法
  const login = async (username: string, password: string) => {
    try {
      const response = await loginApi(username, password) as any
      token.value = response.token
      Cookies.set('token', response.token, { expires: 7 })
      return response
    } catch (error) {
      throw error
    }
  }

  const getUserInfo = async () => {
    try {
      const response = await getUserInfoApi() as any
      userInfo.value = response
      return response
    } catch (error) {
      throw error
    }
  }

  const initUserInfo = async () => {
    if (token.value) {
      try {
        await getUserInfo()
      } catch (error) {
        console.error('初始化用户信息失败:', error)
        logout()
      }
    }
  }

  const logout = () => {
    token.value = ''
    userInfo.value = null
    Cookies.remove('token')
  }

  // 用户管理相关方法
  const fetchUserList = async (params: UserQueryDTO = {}) => {
    loading.value = true
    try {
      const response = await getUserListApi(params) as any
      userList.value = response.records
      userTotal.value = response.total
      return response
    } catch (error) {
      throw error
    } finally {
      loading.value = false
    }
  }

  const createUser = async (data: UserCreateDTO) => {
    try {
      const response = await createUserApi(data)
      // 创建成功后刷新列表
      await fetchUserList()
      return response
    } catch (error) {
      throw error
    }
  }

  const updateUser = async (id: number, data: UserUpdateDTO) => {
    try {
      const response = await updateUserApi(id, data)
      // 更新成功后刷新列表
      await fetchUserList()
      return response
    } catch (error) {
      throw error
    }
  }

  const deleteUser = async (id: number) => {
    try {
      const response = await deleteUserApi(id)
      // 删除成功后刷新列表
      await fetchUserList()
      return response
    } catch (error) {
      throw error
    }
  }

  const resetPassword = async (id: number, newPassword: string) => {
    try {
      const response = await resetPasswordApi(id, newPassword)
      return response
    } catch (error) {
      throw error
    }
  }

  const checkUsername = async (username: string) => {
    try {
      const response = await checkUsernameApi(username)
      return response
    } catch (error) {
      throw error
    }
  }

  const checkEmail = async (email: string) => {
    try {
      const response = await checkEmailApi(email)
      return response
    } catch (error) {
      throw error
    }
  }

  const checkPhone = async (phone: string) => {
    try {
      const response = await checkPhoneApi(phone)
      return response
    } catch (error) {
      throw error
    }
  }

  return {
    // 认证相关
    token,
    userInfo,
    isLoggedIn,
    login,
    getUserInfo,
    initUserInfo,
    logout,

    // 用户管理相关
    userList,
    userTotal,
    loading,
    fetchUserList,
    createUser,
    updateUser,
    deleteUser,
    resetPassword,
    checkUsername,
    checkEmail,
    checkPhone
  }
})
